<template>
  <div ref="creativeperformanceNewRef">
    <basic-container>
      <div class="header">
        <!--日期与模板-->
        <div class="header-up">
          <div class="date-template">
            <div class="dt-item">
              <el-date-picker
                size="mini"
                v-model="updateDateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="() =>{
                this.page.current =1
                this.onLoad()}"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="dt-item">
              <el-date-picker
                size="mini"
                v-model="creativeCreativeTime"
                type="date"
                value-format="yyyy-MM-dd 00:00:00"
                range-separator="-"
                placeholder="素材创建时间"
                @change="() =>{
                this.page.current =1
                this.onLoad()}"
                :picker-options="pickerOptions">
              </el-date-picker></div>
            <div class="dt-item">
              <el-date-picker
                size="mini"
                v-model="creativeDemandCreativeTime"
                type="date"
                value-format="yyyy-MM-dd 00:00:00"
                range-separator="-"
                placeholder="需求提出时间"
                @change="() =>{
                this.page.current =1
                this.onLoad()}"
                :picker-options="pickerOptions">
              </el-date-picker></div>
            <div class="dt-item">
              <el-button size="mini" @click="tableColumnDrawer = true">自定义列</el-button>
            </div>
            <div class="dt-item">
              <el-button size="mini" @click="kpiDrawer = true">kpi指标</el-button>
            </div>
            <div class="dt-item">
              <el-button size="mini" type="primary" @click="()=>{
                this.changeDefualtTemplate()
                this.onLoad()
              }">默认模板</el-button>
            </div>
            <div class="dt-item">
              <el-select v-model="templateSelect" placeholder="请选择" style="width: 125px; margin-right: 5px" size="mini"
                         @change="templateChange">
                <el-option
                  v-for="item in templateList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    <el-button size="mini" @click="deleteTemplate(item.id, item.name)" type="text"><i
                      class="el-icon-delete"/></el-button>
                  </span>
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <!--筛选条件-->
        <cs-filter-query ref="csFilterQueryRef" :options="filterQueryOptions"
                         @change="handleChangeFilter"></cs-filter-query>
      </div>
      <div class="tab-header clearfix">
        <div class="tab-header-left">
          <!--<span>显示模板</span>-->
          <!--<el-select v-model="templateSelect" placeholder="请选择" style="width: 125px; margin-right: 5px" size="mini"-->
          <!--           @change="templateChange">-->
          <!--  <el-option-->
          <!--    v-for="item in templateList"-->
          <!--    :key="item.id"-->
          <!--    :label="item.name"-->
          <!--    :value="item.id">-->
          <!--    <span style="float: left">{{ item.name }}</span>-->
          <!--    <span style="float: right; color: #8492a6; font-size: 13px">-->
          <!--          <el-button size="mini" @click="deleteTemplate(item.id, item.name)" type="text"><i-->
          <!--            class="el-icon-delete"/></el-button>-->
          <!--        </span>-->
          <!--  </el-option>-->
          <!--</el-select>-->
          <!--<el-button type="primary" size="mini" @click="handleModelOpen">保存为模板</el-button>-->
        </div>
        <div class="tab-header-right">
          <el-tooltip class="item" effect="dark" content="清空" placement="top">
            <el-button icon="el-icon-delete" size="mini" circle @click="$refs.csFilterQueryRef.clear()"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="保存模板" placement="top">
            <el-button icon="myicon icon-save" size="mini" circle @click="handleModelOpen"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="导出" placement="top">
            <el-button icon="el-icon-download" size="mini" circle @click="exportExcel"></el-button>
          </el-tooltip>
        </div>
      </div>
      <!--图片表格-->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        show-summary
        :summary-method="summaryMethod"
        @sort-change="sortTableData"
        :header-cell-style="iHeaderCellStyle"
        style="width: 100%">
        <el-table-column
          v-for="item in tableColumnData"
          :prop="item.value"
          :label="item.label"
          :sortable="item.sortable"
          :width="item.width?item.width:''"
          :fixed="item.fixed"
          :render-header="item.renderHeader">
          <template v-slot="{row}" v-if="item.value==='creativeUrl'">
            <div @click="handleMediaPreview(row)" style="display: inline-block"
                 :class="row.type == 1?'play-icon':''">
              <video
                v-if="row.type == 1"
              :src="row.creativeUrl"
              style="width: 100%"
            ></video>
              <img
                v-else
                width="100%"
                :src="row.creativeUrl"
              />

            </div>
          </template>
          <template v-slot="{row}" v-else-if="item.value==='shortId'">
            <div><a href="javascript: void(0)" style="text-decoration: underline;" @click="onCreativeTagsClick(row)">{{
                row.shortId
              }}</a></div>
          </template>
          <template v-slot="{row}" v-else-if="item.value==='designer'">
            {{ designerChange(row.designer) }}
          </template>
          <template v-slot="{row}" v-else-if="item.value==='operator'">
            {{ designerChange(row.operator) }}
          </template>
          <template v-slot="{row}" v-else-if="item.value==='ads'">
            {{ countAds(row) }}
          </template>
          <template v-slot="{row}" v-else-if="item.value==='ctr'">
            {{ row.ctr }}%
          </template>
          <template v-slot="{row}" v-else-if="item.value==='cvr'">
            {{ row.cvr }}%
          </template>
          <template v-slot="{row}" v-else-if="item.value==='os'">
            {{ codeOS(row.os) }}
          </template>
          <template v-slot="{row}" v-else-if="item.value==='installCost'">
            {{ row.installCost | thousandSeparator }}
          </template>
          <template v-slot="{row}" v-else-if="item.value==='platform'">
            <div style="display: flex;flex-wrap: wrap;">
              <div style="width: 20px;margin-right: 4px"
                   v-for="(item,index) in platformLogo(row.platform)"
                   :key="index">
                <img style="width: 100%" :src="item.url" :title="item.name">
              </div>
            </div>
          </template>
          <template v-slot="{row}" v-else-if="item.value==='performanceName'">
            <el-tooltip effect="dark" :content="row.performanceName" placement="left">
              <span class="over-flow">{{ row.performanceName }}</span>
            </el-tooltip>
          </template>
          <template v-slot="{row}" v-else-if="item.value==='localFilename'">
            <el-tooltip effect="dark" :content="row.localFilename" placement="left">
              <span class="over-flow">{{ row.localFilename }}</span>
            </el-tooltip>
          </template>
          <template v-slot="{row}" v-else-if="item.value==='country'">
            <el-tooltip effect="dark" :content="row.country" placement="left">
              <span class="over-flow">{{ row.country }}</span>
            </el-tooltip>
          </template>
          <template slot-scope="{ row }" v-else-if="item.value==='onlineStatus'">
            <el-tag type="danger" v-if="row.status !== 2 && row.onlineStatus === 1">违规</el-tag>
            <el-tag type="success" v-else-if="row.onlineStatus === 1">在线</el-tag>
            <el-tag type="info" v-else>未在线</el-tag>
          </template>
        </el-table-column>
        <!--显隐-->
        <el-table-column
          fixed="right"
          label="操作"
          width="50">
          <template v-slot="{row}">
            <el-tooltip content="查看" placement="top">
              <el-button size="small" icon="el-icon-view" type="text" @click="checkRow(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--底部-->
      <div class="bottom-page clearfix">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </basic-container>
    <el-drawer
      title="列显隐"
      size="800px"
      :visible.sync="tableColumnDrawer2"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
      ref="drawer"
      @close="handleCloseTableColSet"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <el-transfer
          filterable
          v-model="tableColumnValue"
          :data="tableColumnData"
          :titles="['隐藏', '显示']"
          :props="{key: 'value',label: 'label'}"
          @left-check-change="filterLeftTableColumnData">
        </el-transfer>
      </cs-drawer-container>
    </el-drawer>
    <el-drawer
      title="自定义列"
      size="800px"
      :visible.sync="tableColumnDrawer"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <div class="drawer-box">
          <div class="drawer-box-left">
            <div class="drawer-box-left-input">
              <el-input v-model="headerQueryIntputLeft" size="mini" prefix-icon="el-icon-search"
                        placeholder="请输入搜索内容" clearable></el-input>
            </div>
            <div class="drawer-box-left-tab">
              <el-tabs type="border-card">
                <el-tab-pane label="基础指标">
                  <el-checkbox-group v-model="checkedBaseTarget">
                    <el-checkbox v-for="item in targetSearchData" :label="item.value" :key="item.value"
                                 :disabled="item.disabled"
                                 @change="handleCheckedDimCol($event,item)">{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-tab-pane>
                <el-tab-pane label="媒体事件">
                  <!--<el-checkbox :indeterminate="bigoIsIndeterminate" v-model="bigoCheckAll" @change="handleBigoCheckAllChange">bigo</el-checkbox>-->
                  <!--<div style="margin: 5px 0;"></div>-->
                  <el-checkbox-group v-if="bigoEventList.length > 0" v-model="checkedBigoEvent">
                    <el-checkbox class="event-checkbox" v-for="item in bigoSearchData" :label="item.value"
                                 :key="item.value"
                                 :disabled="item.disabled"
                                 @change="handleCheckedDimCol($event,item)">{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                  <el-checkbox-group v-if="facebookEventList.length > 0" v-model="checkedFacebookEvent">
                    <el-checkbox class="event-checkbox" v-for="item in facebookSearchData" :label="item.value"
                                 :key="item.value"
                                 :disabled="item.disabled"
                                 @change="handleCheckedDimCol($event,item)">{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                  <el-checkbox-group v-if="kwaiEventList.length > 0" v-model="checkedKwaiEvent">
                    <el-checkbox class="event-checkbox" v-for="item in kwaiSearchData" :label="iitem.value"
                                 :key="item.value"
                                 :disabled="item.disabled"
                                 @change="handleCheckedDimCol($event,item)">{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                  <el-checkbox-group v-if="tiktokEventList.length > 0" v-model="checkedTiktokEvent">
                    <el-checkbox class="event-checkbox" v-for="item in tiktokSearchData" :label="item.value"
                                 :key="item.value"
                                 :disabled="item.disabled"
                                 @change="handleCheckedDimCol($event,item)">{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
          <div class="drawer-box-right">
            <el-input v-model="headerQueryIntputRight" size="mini" prefix-icon="el-icon-search"
                      placeholder="请输入搜索内容" clearable></el-input>
            <div class="select-label">已选{{ tableHeaderOpt.length }}列</div>
            <draggable class="tableHeaderOpt" v-model="tableHeaderOpt" chosenClass="chosen" forceFallback="true"
                       group="people"
                       filter=".forbid"
                       animation="100"
                       :move="onMove">
              <transition-group>
                <div :class="isDisabled(item.value)?'drag-box forbid':'drag-box'"
                     v-for="item in rightSearchData" :key="item.value">
                  <div class="drag-box-left">
                    <i class="myicon icon-igw-l-menu-2"></i>
                    <span>{{ item.label }}</span>
                  </div>
                  <div class="drag-box-right" v-show="!isDisabled(item.value)"><i class="myicon icon-zhiding"
                                                                                  @click="upCheckedCol(item)"></i><i
                    class="myicon icon-cha" @click="removeCheckedCol(item)"></i>
                  </div>
                </div>
              </transition-group>
            </draggable>
          </div>
        </div>
        <el-button slot="bottom" size="mini" type="primary" @click="createReport">生成报告</el-button>
      </cs-drawer-container>
    </el-drawer>
    <el-dialog :visible.sync="saveDialog" append-to-body width="30%"
               :close-on-click-modal="false" :show-close="false">
      <div>
        <el-form ref="modelFormRef" :model="modelForm" :rules="modelRules"
                 style="margin: 0 auto;width: 80%;text-align: center">
          <el-form-item prop="modelFormat">
            <el-radio-group v-model="modelForm.modelFormat">
              <el-radio label="0" @change="setTemplateName(true)">
                保存为新模板
              </el-radio>
              <el-radio label="1" @change="setTemplateName(false)" :disabled="templateList.length === 0">覆盖当前的模板
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="modelName" label="模板名：" style="position: relative">
            <el-input size="mini" placeholder="请输入模板名称" v-model="modelForm.modelName"/>
            <span v-if="modelForm.modelFormat === '1'"
                  style="color: #f56c6c; position: absolute; left: 0; top: 86px; width: 200px; text-align: left; font-size: 12px">您可以对现有模板重命名</span>
          </el-form-item>
          <el-form-item style="margin-top: 45px">
            <el-button type="primary" size="mini" @click="saveModel" :disabled="saveTemplateloading">确定</el-button>
            <el-button size="mini" @click="saveDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog
      :visible="creativeInfoDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :append-to-body="true"
      style="text-align: center"
      :before-close="
        () => {
        creativeInfoDialog.dialogVisible = false;
        }
      "
    >
      <creative-info v-if="creativeInfoDialog.dialogVisible" ref="creativeInfo"
                     :creative-id="creativeInfoDialog.creativeId" :main-date="updateDateRange"></creative-info>
    </el-dialog>
    <creative-performance-detail width="80%" ref="creativePerformanceDetail"></creative-performance-detail>
    <!--预览弹窗-->
    <creative-card-preview v-model="mediaPreviewDialog.dialogVisible"
                           :media-preview="currentCreative"></creative-card-preview>
    <el-drawer
      title="KPI指标"
      size="800px"
      :visible.sync="kpiDrawer"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <div class="kpi-box">
          <el-form ref="kpiForm" label-position="top" :model="kpiForm" label-width="80px">
            <el-form-item label="KPI">
              <el-radio-group v-model="kpiForm.target">
                <el-radio :label="item" v-for="item in kpiTargetList" :key="item">{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-table
                :data="kpiForm.filterItems"
                style="width: 100%"
              >
                <el-table-column
                  prop="platform"
                  label="媒体">
                  <template v-slot="{row}">
                    <el-select size="mini" v-model="row.platform" placeholder="请选择">
                      <el-option
                        v-for="item in platformList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="os"
                  label="操作系统">
                  <template v-slot="{row}">
                    <el-select size="mini" v-model="row.os" placeholder="请选择">
                      <el-option
                        v-for="item in oslist"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="country"
                  label="投放地区">
                  <template v-slot="{row}">
                    <el-select filterable clearable size="mini" v-model="row.country" placeholder="请选择">
                      <el-option
                        v-for="item in nationList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="standard"
                  label="达标"
                  width="200">
                  <template v-slot="{row}">
                    <el-select style="width: 100px" size="mini" v-model="row.standard.condition">
                      <el-option
                        v-for="item in compareList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <el-input style="width: 180px" type="number" size="mini" v-model="row.standard.value"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="exceed"
                  label="超标"
                  width="200">
                  <template v-slot="{row}">
                    <el-select style="width: 100px" size="mini" v-model="row.exceed.condition">
                      <el-option
                        v-for="item in compareList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <el-input type="number" size="mini" v-model="row.exceed.value"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  width="50">
                  <template v-slot="{row, column, $index}">
                    <i class="el-icon-delete" style="cursor: pointer" @click="removeFilterItems($index)"></i>
                  </template>
                </el-table-column>
              </el-table>
              <el-link type="primary" @click="addFilterItems">+ 添加指标</el-link>
            </el-form-item>
          </el-form>
        </div>
        <template v-slot:bottom>
          <el-button size="mini" type="primary" @click="submitKpiTarget">保存</el-button>
          <el-button size="mini" @click="kpiDrawer = false">取消</el-button>
        </template>
      </cs-drawer-container>
    </el-drawer>
  </div>
</template>

<script>
import {
  getDesignerList,
  getList2,
  getSubmitter,
  getTemplateList,
  saveTemplate,
  deleteTemplate,
  getEventCreativeGroup,
  exportExcel2, submitKpiConfig, getKpiConfig,
} from "@/api/offer/creativeperformance";
import creativePerformanceDetail from '@/views/creativeReport/components/creativeperformancedetail'
import {getSysDictList} from "@/api/system/dict";
import {createEventHandler} from "@/util/events";
import {mapGetters} from "vuex";
import Moment from "moment";
import creativeInfo from "./components/creativeInfo";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import CsFilterQuery from "@/components/CsFilterQuery/CsFilterQuery";
import draggable from "vuedraggable"
import _ from "lodash";
import CreativeCardPreview from "@/components/CreativeCardPreview/CreativeCardPreview";
import KpiConfig from "@/views/creativeReport/components/KpiConfig";
import {columnTip} from "@/util/util";
import {mapState} from "vuex";
import {platformLogo} from "../../util/beetles";
import {getAllUser} from "@/api/user";

export default {
  name: 'CreativePerformance',
  components: {
    creativePerformanceDetail,
    creativeInfo,
    CsDrawerContainer,
    CsFilterQuery,
    CreativeCardPreview,
    draggable,
    KpiConfig
  },
  data() {
    let checkShortId = (rule, value, callback) => {
      const shortReg = /^\d{3,6}$/;
      if (value !== '' && !shortReg.test(value)) {
        callback(new Error('请输入3-6位数字!'))
      } else {
        callback()
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      resultList: [],
      designerList: [],
      now: "",
      lastWeek: "",
      submitterList: [],
      countryList: [],
      platformList: [],
      nationList: [],
      query: {},
      rules: {
        shortId: [{required: false, validator: checkShortId, trigger: 'change'}],
      },
      updateDateRange: [],
      loading: true,
      page: {
        size: 10,
        current: 1,
        total: 0,
      },
      selectionList: [],
      mediaPreviewDialog: {
        dialogVisible: false,
        // dialogType: "image", //image or video
        // previewUrl: "",
      },
      creativeInfoDialog: {
        dialogVisible: false,
        name: '',
        creativeId: '',
      },
      isAdvSharedOffer: false,
      // marco
      // 显隐抽屉
      saveTemplateloading: false,
      tableColumnDrawer: false,
      tableColumnValue: [],
      defaultTableColumnValue: ["creativeUrl", "shortId", "performanceName", "localFilename", "offerName", "designer", "platform", "country", "allExpend", "impressions", "clicks", "ctr", "installCost", "cvr"],
      tableColumnData: [],
      defaultTableColumnData: [
        {
          value: "creativeUrl",
          label: "素材",
          width: 150,
          disabled: true,
          checked: true,
          fixed: true
        },
        {
          value: "shortId",
          label: "素材Id",
          width: 100,
          disabled: true,
          checked: true,
          fixed: true,
          renderHeader: (h, {column}) => {
            return columnTip(h, column, '点击可查看单个素材的详细数据和信息')
          }
        },
        {
          value: "performanceName",
          label: "素材名称",
          checked: true
        },
        {
          value: "localFilename",
          label: "本地文件名",
          width: 150,
          checked: true
        },
        // {
        //   label: "状态",
        //   value: "onlineStatus",
        // },
        {
          value: "offerName",
          label: "订单名",
          width: 100,
          checked: true
        },
        {
          value: "designer",
          label: "设计师",
          width: 100,
          checked: true
        },
        {
          label: '优化师',
          value: 'operator',
        },
        {
          value: "platform",
          label: "媒体",
          width: 100,
          checked: true,
          renderHeader: (h, {column}) => {
            return columnTip(h, column, '广告/素材实际产生归因数据的平台')
          }
        },
        {
          value: "country",
          label: "投放地区",
          width: 100,
          checked: true,
          renderHeader: (h, {column}) => {
            return columnTip(h, column, '广告/素材实际产生归因数据的国家/地区')
          }
        },
        // {
        //   label: "在线天数",
        //   value: "onlineDays",
        // },
        {
          value: "os",
          label: "操作系统",
          width: 100
        },
        {
          value: "ads",
          label: "关联广告数",
          sortable: 'custom',
          width: 120
        },
        {
          value: "allExpend",
          label: "花费",
          sortable: 'custom',
          width: 100,
          checked: true
        },
        {
          value: "impressions",
          label: "曝光",
          sortable: 'custom',
          width: 100,
          checked: true
        },
        {
          value: "clicks",
          label: "点击",
          sortable: 'custom',
          width: 100,
          checked: true
        },
        {
          value: "ctr",
          label: "CTR",
          sortable: 'custom',
          width: 100,
          checked: true
        },
        {
          value: "install",
          label: "安装",
          sortable: 'custom',
          width: 100,
          checked: true,
          renderHeader: (h, {column}) => {
            return columnTip(h, column, '<p>在不同媒体/平台，实际对应的字段如下：</p>' +
              '<p>Facebook - install 安装</p>' +
              '<p>Bigo Ads - install 去重安装</p>' +
              '<p>Google Ads - conversions 转化数</p>' +
              '<p>Tiktok - conversions 转化数</p>')
          }
        },
        {
          value: "installCost",
          label: "安装成本",
          sortable: 'custom',
          width: 100,
          checked: true
        },
        {
          value: "cvr",
          label: "CVR",
          sortable: 'custom',
          width: 100
        }, {
          label: '需求ID',
          value: 'requestId',
        }, {
          label: '需求名称',
          value: 'requestName',
        }, {
          label: '素材创建时间',
          value: 'creativeCreativeTime',
          checked: true,
        }, {
          label: '需求提出时间',
          value: 'creativeDemandCreativeTime',
          checked: true,
        }
      ],
      // 模板相关
      templateList: [],
      templateSelect: '',
      templateSelectOld: '',
      templateDefaultName: '',
      saveDialog: false,
      modelForm: {
        modelFormat: '0',
        modelName: '',
      },
      modelRules: {
        modelFormat: [{required: true, message: '请选择模板保存形式', trigger: 'change'}],
        modelName: [{required: true, message: '请输入模板名称', trigger: 'blur'},
          {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'}]
      },
      // 媒体事件
      eventData: [],
      tableData: [],
      filterQueryInfo: {},
      // 排序
      sortList: [],
      // temp
      tableColumnDrawer2: false,
      // 自定义列搜索
      headerQueryIntputLeft: '',
      headerQueryIntputRight: '',
      checkedBaseTarget: [],
      // 自定义列数据
      tableHeaderOpt: [],
      checkedBigoEvent: [],
      // bigo事件
      bigoEventList: [],
      // facebook事件
      facebookEventList: [],
      checkedFacebookEvent: [],
      // kwai事件
      kwaiEventList: [],
      checkedKwaiEvent: [],
      // tiktok事件
      tiktokEventList: [],
      checkedTiktokEvent: [],
      // 半选状态
      bigoIsIndeterminate: false,
      // 全选
      bigoCheckAll: false,
      // 当前素材
      currentCreative: null,
      // kpi抽屉
      kpiDrawer: false,
      oslist: [
        {
          label: 'Android',
          value: '1'
        }, {
          label: 'IOS',
          value: '2'
        }, {
          label: 'Website',
          value: '3'
        }
      ],
      userList: [],
      // kpi指标
      kpiForm: {
        target: '',
        filterItems: []
      },
      // kpi指标
      kpiTargetList: ['花费', '曝光', '点击', 'CTR', '安装', 'CVR', '安装成本'],
      // 对比指标
      compareList: [
        {
          label: '>=',
          value: '>='
        }, {
          label: '>',
          value: '>'
        }, {
          label: '<',
          value: '<'
        }, {
          label: '<=',
          value: '<='
        }
      ],
      creativeCreativeTime: null,
      creativeDemandCreativeTime: null
    }
  },
  computed: {
    ...mapGetters(["permission", "offer", "userInfo"]),
    ...mapState({
      offerId: state => state.user.offer
    }),
    // marco
    // 选择的媒体事件
    selectedEventData() {
      return this.eventData.filter(item => this.tableHeaderOpt.map(item => item.value).includes(item.value)).map(item => item.value).join(',')
    },
    // 筛选组件配置
    filterQueryOptions() {
      return [
        {
          value: 'shortId',
          label: '素材ID',
        },
        {
          value: 'name',
          label: '素材名',
        },
        {
          value: 'localFilename',
          label: '本地文件名',
        },
        {
          value: 'type',
          label: '素材类型',
          children: [
            {
              value: '0',
              label: '图片',
            },
            {
              value: '1',
              label: '视频',
            }
          ]
        },
        {
          value: 'designer',
          label: '设计师',
          queryList: this.userList
        }, {
          value: 'operator',
          label: '优化师',
          queryList: this.userList
        }, {
          value: 'platform',
          label: '投放媒体',
          children: this.platformList
        }, {
          value: 'country',
          label: '投放地区',
          queryList: this.nationList
        },
        {
          value: 'os',
          label: '操作系统',
          children: this.oslist
        },
        {
          value: 'requestId',
          label: '需求ID'
        }, {
          value: 'requestName',
          label: '需求名称'
        }]
    },
    // 右边搜索栏
    rightSearchData() {
      if (this.headerQueryIntputRight) {
        return this.tableHeaderOpt.filter(item => {
          const input = this.headerQueryIntputRight.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.tableHeaderOpt
      }
    },
    // 基础指标搜索
    targetSearchData() {
      if (this.headerQueryIntputLeft) {
        return this.defaultTableColumnData.filter(item => {
          const input = this.headerQueryIntputLeft.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.defaultTableColumnData
      }
    },
    // bigo搜索
    bigoSearchData() {
      if (this.headerQueryIntputLeft) {
        return this.bigoEventList.filter(item => {
          const input = this.headerQueryIntputLeft.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.bigoEventList
      }
    },
    // facebook搜索
    facebookSearchData() {
      if (this.headerQueryIntputLeft) {
        return this.facebookEventList.filter(item => {
          const input = this.headerQueryIntputLeft.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.facebookEventList
      }
    },
    // kwai搜索
    kwaiSearchData() {
      if (this.headerQueryIntputLeft) {
        return this.kwaiEventList.filter(item => {
          const input = this.headerQueryIntputLeft.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.kwaiEventList
      }
    },
    // tiktok搜索
    tiktokSearchData() {
      if (this.headerQueryIntputLeft) {
        return this.tiktokEventList.filter(item => {
          const input = this.headerQueryIntputLeft.toLowerCase()
          const label = item.label.toLowerCase()
          return label.includes(input)
        })
      } else {
        return this.tiktokEventList
      }
    },
  },
  watch: {
    // 第一次载入模板时校对不可选的项目
    tableColumnValue: {
      handler: 'filterTableColumnData',
      immediate: true
    },
    tableHeaderOpt: {
      handler() {
        this.checkPlateformType()
      }
    },
    offerId: {
      handler:async function () {
        await this.getEventCreativeGroup()
        await this.getTemplateList()
        // 第一次进入显示上次模板
        if (this.templateList.length > 0) {
          this.handleTemplateList(this.templateList[0].basicData)
          this.templateSelect = this.templateList[0].id
          this.templateSelectOld = this.templateList[0].id
        } else {
          this.changeDefualtTemplate()
        }
        //window.addEventListener('keyup', this.submitForm) //监听键盘事件
        this.updateDateRange = [Moment().subtract(7, "days").format("yyyy-MM-DD"), Moment().subtract(1, "days").format("yyyy-MM-DD")];
        this.query.beginDate = this.updateDateRange[0];
        this.query.endDate = this.updateDateRange[1];
        await this.getKpiConfig()
        await this.onLoad()
      }
    }
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if (self.eventHandler) {
      self.eventHandler.clear();
    }
    next();
  },

  async created() {
    this.refresh()
    // this.initHeaderCol()
    await this.getEventCreativeGroup()
    await this.getTemplateList()
    this.getKpiConfig()
    // 第一次进入显示上次模板
    if (this.templateList.length > 0) {
      this.handleTemplateList(this.templateList[0].basicData)
      this.templateSelect = this.templateList[0].id
      this.templateSelectOld = this.templateList[0].id
    } else {
      this.changeDefualtTemplate()
    }
    //window.addEventListener('keyup', this.submitForm) //监听键盘事件
    this.updateDateRange = [Moment().subtract(7, "days").format("yyyy-MM-DD"), Moment().subtract(1, "days").format("yyyy-MM-DD")];
    this.query.beginDate = this.updateDateRange[0];
    this.query.endDate = this.updateDateRange[1];
    await this.onLoad()
    // this.eventHandler = createEventHandler("offerCenter").addListener(
    //   async (event) => {
        // if (
        //   event.message == "offerChanged" &&
        //   event.offerId &&
        //   event.offerId !== ""
        // ) {
          // this.offer = event.offerId;
          // this.refresh();
          // await this.getEventCreativeGroup()
          // await this.getTemplateList()
          // 第一次进入显示上次模板
          // if (this.templateList.length > 0) {
          //   this.handleTemplateList(this.templateList[0].basicData)
          //   this.templateSelect = this.templateList[0].id
          //   this.templateSelectOld = this.templateList[0].id
          // } else {
          //   this.changeDefualtTemplate()
          // }

          // this.updateDateRange = [Moment().subtract(7, "days").format("yyyy-MM-DD"), Moment().subtract(1, "days").format("yyyy-MM-DD")];
          // this.query.beginDate = this.updateDateRange[0];
          // this.query.endDate = this.updateDateRange[1];
          // await this.onLoad();
        // }
    //   }
    // );
    // this.refresh();
  },
  mounted() {
    console.dir(this.$refs.creativeperformanceNewRef)
    this.offsetHeight = this.$refs.creativeperformanceNewRef.offsetHeight
  },
  methods: {
    thousandSeparator(num) {
      let s = num.toString();
      let div = s.indexOf('.');
      let sign = (num < 0) ? '-' : '';
      let intPart = (div == -1) ? s : s.substring(0, div);
      let dotPart = (div == -1) ? '' : s.substring(div);
      let finalIntPart = '';
      while (intPart.length > 3) {
        finalIntPart = ',' + intPart.substring(intPart.length - 3) + finalIntPart;
        intPart = intPart.substring(0, intPart.length - 3);
      }
      return sign + intPart + finalIntPart + dotPart;
    },
    summaryMethod({columns, data}) {
      const ign = ["creativeUrl", "shortId", "performanceName", "localFilename", "offerName", "designer", "platform", "country"]
      const sums = [];
      let allExpendSum = 0;
      let impressionsSum = 0;
      let clicksSum = 0;
      let ctrSum = 0;
      let installSum = 0;
      let cvrSum = 0;
      let installCostSum = 0;
      if (data.length > 0) {
        data.forEach((row) => {
          allExpendSum += parseFloat(row.allExpend)
          impressionsSum += parseFloat(row.impressions)
          clicksSum += parseFloat(row.clicks)
          ctrSum += parseFloat(row.ctr)
          installSum += parseFloat(row.install)
          cvrSum += parseFloat(row.cvr)
          installCostSum += parseFloat(row.installCost)
        })
      }
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          if ([0].includes(index)) {
            sums[index] = '合计'
          } else if (column.label && column.label === "花费") {
            sums[index] = this.thousandSeparator(allExpendSum.toFixed(2))
          } else if (column.label && column.label === "曝光") {
            sums[index] = impressionsSum = this.thousandSeparator(impressionsSum.toFixed(2))
          } else if (column.label && column.label === "点击") {
            sums[index] = clicksSum = this.thousandSeparator(clicksSum.toFixed(2))
          } else if (column.label && column.label === "CTR") {
            sums[index] = ctrSum = this.thousandSeparator(ctrSum.toFixed(2)) + "%"
          } else if (column.label && column.label === "安装") {
            sums[index] = installSum = this.thousandSeparator(installSum.toFixed(2))
          } else if (column.label && column.label === "CVR") {
            sums[index] = cvrSum = this.thousandSeparator(cvrSum.toFixed(2)) + "%"
          } else if (column.label && column.label === "安装成本") {
            sums[index] = installCostSum = this.thousandSeparator(installCostSum.toFixed(2))
          } else {
            // marco
            // sums[index] = this.tableColumnValue.map(item => Number(item[column.property]));
            sums[index] = ''
          }
        });
      }
      return sums;
    },
    previewStyle() {
      let height = window.innerHeight < 300 ? 300 : window.innerHeight - 160;
      return {
        maxWidth: "100%",
        maxHeight: height + "px",
      };
    },
    handleMediaPreview(row) {
      this.currentCreative = row
      // this.mediaPreviewDialog.previewUrl = row.creativeUrl + "?" + (row.updateTime ? row.updateTime.replace(/[ :-]*/gi, "") : 1234);
      // this.mediaPreviewDialog.dialogType = row.type == 0 ? "image" : "video";
      this.mediaPreviewDialog.dialogVisible = true;
    },
    refresh() {
      getDesignerList(this.offer).then((res) => {
        this.designerList = res.data.data.map(item => {
          return {
            label: item.realName,
            value: item.id
          }
        });
      });
      getSysDictList("platforms,nation").then((map) => {
        this.platformList = map['platforms'].map(item => {
          return {
            label: item.dictValue,
            value: item.dictKey
          }
        })
        this.nationList = map['nation'].map(item => {
          return {
            label: item.dictKey,
            value: item.dictKey
          }
        })
      });
      getAllUser().then((res) => {
        this.userList = res.data.data.map(item => {
          return {
            label: item.realName,
            value: item.id
          }
        })
      })
    },
    /**
     * 用来转换设计师id （方法）
     */
    designerChange(row) {
      let designers = row.split(",");
      let designerList = this.designerList;
      let name = [];
      for (let i in designerList) {
        let designerId = designerList[i].id;
        let designerName = designerList[i].realName;
        for (let j in designers) {
          let designer = designers[j];
          if (designer === designerId) {
            name.push(designerName);
          }
        }
      }
      return name.join(",");
    },
    /**
     * 统计当前素材跑了多少个广告
     * @param row
     * @returns {string}
     */
    countAds(row) {
      let adsArr = row.ads.split(",");
      let res = [...new Set(adsArr)];
      return res.length;
    },
    async exportExcel() {
      const res = await exportExcel2({
        offerId: this.offerId,
        ...this.page,
        beginDate: this.updateDateRange ? this.updateDateRange[0] : null,
        endDate: this.updateDateRange ? this.updateDateRange[1] : null,
        sortList: JSON.stringify(this.sortList),
        ...this.filterQueryInfo,
      })
      let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
      let url = window.URL.createObjectURL(new Blob([res.data]))
      let link = document.createElement("a")
      link.style.display = "none"
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
    },
    dialogType(val) {
      let type;
      let urlTail = val.split(".")[val.split(".").length - 1];
      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlTail)) {
        type = "image";
      } else if (videoList.includes(urlTail)) {
        type = "video";
      }
      return type;
    },
    checkRow(row) {
      // console.log('row', this.tableHeaderOpt.map(item=>item.value))
      this.$refs.creativePerformanceDetail.queryForm = {
        platform: null,
        beginDate: null,
        endDate: null,
        nationList: [],
        updateDateRange: this.updateDateRange,
      }
      this.$refs.creativePerformanceDetail.showDialog({
        creativeId: row.creativeId,
        shortId: row.shortId,
        performanceName: row.performanceName,
        eventData: this.eventData,
        selectedEventData: this.selectedEventData,
        tableColumnValue: this.tableHeaderOpt.map(item => item.value)
      });
    },
    currentChange(currentPage) {
      this.page.current = currentPage;
    },
    sizeChange(pageSize) {
      this.page.size = pageSize;
    },
    onCreativeTagsClick(row) {
      this.$nextTick(() => {
        this.creativeInfoDialog.name = row.performanceName;
        this.creativeInfoDialog.creativeId = row.id;
        this.creativeInfoDialog.dialogVisible = true;
      });
    },
    async onLoad() {
      this.loading = true;
      let sortList = this.sortList
      // marco
      const res = await getList2({
        ...this.page,
        sortList: JSON.stringify(sortList),
      }, {
        beginDate: this.updateDateRange ? this.updateDateRange[0] : null,
        endDate: this.updateDateRange ? this.updateDateRange[1] : null,
        offerId: this.offerId,
        sortList: JSON.stringify(sortList),
        eventData: this.selectedEventData,
        tempId: this.templateSelectOld,
        ...this.filterQueryInfo,
        creativeCreativeTime: this.creativeCreativeTime,
        creativeDemandCreativeTime: this.creativeDemandCreativeTime
      })
      let data = res.data.data;
      this.page.total = data.total;
      this.resultList = res.data.data.records;
      for (let i = 0; i < this.resultList.length; i++) {
        if (this.resultList[i].country != null && this.resultList[i].country != '') {
          let countryList = this.resultList[i].country.split(',');
          let set = new Set();
          countryList.forEach(c => {
            if (c != '') {
              set.add(c);
            }
          });
          this.resultList[i].country = Array.from(set).join(',');
        }
      }
      this.tableData = this.resultList
      // console.log('imageData',this.imageData)
      // console.log('videoData',this.videoData)
      this.loading = false;
      // this.selectionClear();
    },
    // marco
    handleSizeChange(val) {
      this.page.size = val
      this.$refs.csFilterQueryRef.$el.scrollIntoView()
      this.onLoad()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.$refs.csFilterQueryRef.$el.scrollIntoView()
      this.onLoad()
    },
    // 排序
    sortTableData(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.onLoad();
    },
    // 获取模板
    async getTemplateList() {
      const {data: res} = await getTemplateList(this.offerId, 1)
      this.templateList = res.data
    },
    handleModelClose() {
      this.saveDialog = false
      this.getTemplateList()
    },
    handleModelOpen() {
      this.saveDialog = true
      // 设置默认模板名
      this.templateDefaultName = this.userInfo.nick_name + '-' + Moment(new Date()).format('YYYYMMDDHHmmss') + '自定义模板'
      if (this.templateSelect && !isNaN(this.templateSelect)) {
        this.modelForm.modelFormat = '1'
        this.setTemplateName(false)
      } else {
        this.modelForm.modelFormat = '0'
        this.setTemplateName(true)
      }
    },
    findTemplateByName(name) {
      for (let i = 0; i < this.templateList.length; i++) {
        if (this.templateList[i].name === name) {
          return this.templateList[i].id
        }
      }
      return false
    },
    saveTemplate(data) {
      saveTemplate(data).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        })
        this.saveTemplateloading = false
        this.handleModelClose()
      })
    },
    updateTemplate(data) {
      saveTemplate(data).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        })
        this.saveTemplateloading = false
        this.handleModelClose()
      })
    },
    // 更换模板
    templateChange(val) {
      this.templateList.map(item => {
        if (item.id === val) {
          this.modelForm.modelFormat = '0'
          this.modelForm.modelName = this.templateDefaultName
          this.templateSelectOld = item.id
          this.handleTemplateList(item.basicData)
          // updateUseTime(item.id)
        }
      })
      this.onLoad()
    },
    setTemplateName(flag) {
      if (flag) {
        this.modelForm.modelName = this.templateDefaultName
      } else {
        this.templateList.map(item => {
          if (item.id === this.templateSelectOld) {
            this.modelForm.modelName = item.name
          }
        })
      }
    },
    deleteTemplate(id, name) {
      this.$confirm("确定删除模板【" + name + "】?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteTemplate(id).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          })
          this.getTemplateList()
          this.templateSelect = null
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    /**
     * 保存模板
     */
    saveModel() {
      this.saveTemplateloading = true
      this.$refs.modelFormRef.validate(valid => {
        if (valid) {
          const basicData = [...this.checkedBaseTarget, ...this.checkedBigoEvent, ...this.checkedFacebookEvent, ...this.checkedKwaiEvent, ...this.checkedTiktokEvent].join(',')
          let data = {
            'id': this.templateSelectOld,
            'name': this.modelForm.modelName,
            'basicData': basicData,
            'eventData': '',
            'offerId': this.offerId,
            'type': 1
          }
          if (this.modelForm.modelFormat === '0') {
            let id = this.findTemplateByName(data.name)
            if (id) {
              this.$confirm('此模板名已经存在，是否要覆盖该模板？', '提示', {
                confirmButtonText: '覆盖',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                data.id = id
                this.saveTemplate(data)
              })
            } else {
              delete data.id
              this.saveTemplate(data)
            }
          } else if (this.modelForm.modelFormat === '1' && data.id) {
            this.saveTemplate(data)
          } else {
            this.$message({
              type: "error",
              message: "当前未选择覆盖模板！"
            })
          }
        } else {
          this.saveTemplateloading = false
        }
      })
    },
    //获取表格表头显隐事件列表
    async getEventCreativeGroup() {
      const {data: res} = await getEventCreativeGroup(this.offerId)
      this.eventData = res.data.eventData
      this.bigoEventList = this.eventData.filter(item => _.startsWith(item.value, 'bigo')) // 找出bigo开头的事件
      this.facebookEventList = this.eventData.filter(item => _.startsWith(item.value, 'facebook'))
      this.kwaiEventList = this.eventData.filter(item => _.startsWith(item.value, 'kwai'))
      this.tiktokEventList = this.eventData.filter(item => _.startsWith(item.value, 'tiktok'))
    },
    // 获取表格数据
    handleCloseTableColSet() {
      this.onLoad()
    },
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    // 过滤侧边栏不同平添不可选择
    filterTableColumnData(val) {
      const plateforms = ['bigo', 'facebook', 'kwai', 'tiktok']
      this.tableColumnValue.forEach(item => {
        if (item.split('_')[0] === 'bigo') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'kwai' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'facebook') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'kwai' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'kwai') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'tiktok') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'kwai') {
              item.disabled = true
            }
          })
        } else {
          if (!this.tableColumnValue.some(item => plateforms.includes(item.split('_')[0]))) {
            this.tableColumnData.forEach(item => {
              item.disabled = false
            })
          }
        }
      })
    },
    // 左边穿梭栏事件
    filterLeftTableColumnData(val) {
      const plateforms = ['bigo', 'facebook', 'kwai', 'tiktok']
      val.forEach(item => {
        if (item.split('_')[0] === 'bigo') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'kwai' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'facebook') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'kwai' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'kwai') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'tiktok') {
              item.disabled = true
            }
          })
        } else if (item.split('_')[0] === 'tiktok') {
          this.tableColumnData.forEach(item => {
            if (item.value.split('_')[0] === 'bigo' || item.value.split('_')[0] === 'facebook' || item.value.split('_')[0] === 'kwai') {
              item.disabled = true
            }
          })
        }
      })
      if (!val.some(item => plateforms.includes(item.split('_')[0])) && !this.tableColumnValue.some(item => plateforms.includes(item.split('_')[0]))) {
        this.tableColumnData.forEach(item => {
          item.disabled = false
        })
      }
    },
    // 操作系统显示
    codeOS(val) {
      const arr = val ? val.split(',') : []
      let str = ''
      arr.forEach((item, index) => {
        switch (item) {
          case '1':
            str += 'Android'
            break
          case '2':
            str += 'IOS'
            break
          case '3':
            str += 'Website'
            break
          default:
            return
        }
        str += index < arr.length - 1 ? ',' : ''
      })
      return str
    },
    handleChangeFilter(val) {
      this.filterQueryInfo = val
      this.page.current = 1;
      this.onLoad()
    },
    // 维度选择框事件
    handleCheckedDimCol(event, val) {
      if (event) {
        // 添加对象
        this.tableHeaderOpt.push(val)
      } else {
        // 删除对象
        this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
          // 数组中的对象
          return !_.isEqual(n, val) // 比较对象
        })
      }
    },
    //禁止拖动到id为1的对象
    onMove(e) {
      // console.log(e.relatedContext.element.value)
      const dis = this.defaultTableColumnData.filter(item => item.disabled).map(item => item.value)
      if (dis.includes(e.relatedContext.element.value)) return false;
      return true;
    },
    // 禁用的行
    isDisabled(value) {
      if (value === 'creativeUrl' || value === 'shortId') {
        return true
      } else {
        return false
      }
    },
    // 移除已选择列
    removeCheckedCol(val) {
      this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
        // 数组中的对象
        return !_.isEqual(n, val) // 比较对象
      })
      this.checkedBaseTarget = _.remove(this.checkedBaseTarget, function (n) {
        // 数组中的对象
        return n !== val.value // 比较对象
      })
      this.checkedBigoEvent = _.remove(this.checkedBigoEvent, function (n) {
        // 数组中的对象
        return n !== val.value // 比较对象
      })
      this.checkedFacebookEvent = _.remove(this.checkedFacebookEvent, function (n) {
        // 数组中的对象
        return n !== val.value // 比较对象
      })
      this.checkedKwaiEvent = _.remove(this.checkedKwaiEvent, function (n) {
        // 数组中的对象
        return n !== val.value // 比较对象
      })
      this.checkedTiktokEvent = _.remove(this.checkedTiktokEvent, function (n) {
        // 数组中的对象
        return n !== val.value // 比较对象
      })
    },
    // 置顶已选择列
    upCheckedCol(val) {
      const dis = this.defaultTableColumnData.filter(item => item.disabled)
      this.tableHeaderOpt = _.remove(this.tableHeaderOpt, function (n) {
        // 数组中的对象
        return !_.isEqual(n, val) // 比较对象
      })
      this.tableHeaderOpt.splice(dis.length, 0, val)
      // this.tableHeaderOpt.unshift(val)
    },
    // 侧边生成报告
    createReport() {
      this.tableColumnData = _.cloneDeep(this.tableHeaderOpt)
      this.tableColumnDrawer = false
      this.page.current =1
      this.onLoad()
    },
    // 全选bigo
    handleBigoCheckAllChange(val) {
      this.checkedBigoEvent = val ? this.bigoEventList : [];
      this.isIndeterminate = false;
    },
    // 校验平台
    checkPlateformType() {
      if (this.tableHeaderOpt.some(item => _.startsWith(item.value, 'bigo'))) {
        this.disabledPlateform('bigo')
      } else if (this.tableHeaderOpt.some(item => _.startsWith(item.value, 'facebook'))) {
        this.disabledPlateform('facebook')
      } else if (this.tableHeaderOpt.some(item => _.startsWith(item.value, 'kwai'))) {
        this.disabledPlateform('kwai')
      } else if (this.tableHeaderOpt.some(item => _.startsWith(item.value, 'tiktok'))) {
        this.disabledPlateform('tiktok')
      } else {
        this.disabledPlateform('none')
      }
    },
    disabledPlateform(type) {
      switch (type) {
        case 'bigo':
          this.bigoEventList.forEach(item => {
            item.disabled = false
          })
          this.facebookEventList.forEach(item => {
            item.disabled = true
          })
          this.kwaiEventList.forEach(item => {
            item.disabled = true
          })
          this.tiktokEventList.forEach(item => {
            item.disabled = true
          })
          break
        case 'facebook':
          this.bigoEventList.forEach(item => {
            item.disabled = true
          })
          this.facebookEventList.forEach(item => {
            item.disabled = false
          })
          this.kwaiEventList.forEach(item => {
            item.disabled = true
          })
          this.tiktokEventList.forEach(item => {
            item.disabled = true
          })
          break
        case 'kwai':
          this.bigoEventList.forEach(item => {
            item.disabled = true
          })
          this.facebookEventList.forEach(item => {
            item.disabled = true
          })
          this.kwaiEventList.forEach(item => {
            item.disabled = false
          })
          this.tiktokEventList.forEach(item => {
            item.disabled = true
          })
          break
        case 'tiktok':
          this.bigoEventList.forEach(item => {
            item.disabled = true
          })
          this.facebookEventList.forEach(item => {
            item.disabled = true
          })
          this.kwaiEventList.forEach(item => {
            item.disabled = true
          })
          this.tiktokEventList.forEach(item => {
            item.disabled = false
          })
          break
        default:
          this.bigoEventList.forEach(item => {
            item.disabled = false
          })
          this.facebookEventList.forEach(item => {
            item.disabled = false
          })
          this.kwaiEventList.forEach(item => {
            item.disabled = false
          })
          this.tiktokEventList.forEach(item => {
            item.disabled = false
          })
      }
    },
    // 初始化表头
    initHeaderCol() {
      const dimCol = this.defaultTableColumnData.filter(item => item.checked)
      this.tableHeaderOpt = [...dimCol]
      this.tableColumnData = [...this.tableHeaderOpt]
    },
    // 切换默认模板
    changeDefualtTemplate() {
      this.tableHeaderOpt = this.defaultTableColumnData.filter(item => item.checked)
      this.checkedBaseTarget = this.tableHeaderOpt.map(item => item.value)
      this.tableColumnData = [...this.tableHeaderOpt]
      this.templateSelect = ''
      this.checkedBigoEvent = []
      this.checkedFacebookEvent = []
      this.checkedKwaiEvent = []
      this.checkedTiktokEvent = []
      this.page.current =1
    },
    // 处理模板
    handleTemplateList(templates) {
      // console.log(templates)
      const tempArr = templates.split(',')
      const allCol = [...this.defaultTableColumnData, ...this.eventData]
      this.tableColumnData = allCol.filter(item => tempArr.includes(item.value))
      this.tableHeaderOpt = [...this.tableColumnData]
      // 基础指标选择框
      this.checkedBaseTarget = []
      this.defaultTableColumnData.forEach(item => {
        if (tempArr.includes(item.value)) {
          this.checkedBaseTarget.push(item.value)
        }
      })
      this.checkedBigoEvent = []
      this.bigoEventList.forEach(item => {
        if (tempArr.includes(item.value)) {
          this.checkedBigoEvent.push(item.value)
        }
      })
      this.checkedFacebookEvent = []
      this.facebookEventList.forEach(item => {
        if (tempArr.includes(item.value)) {
          this.checkedFacebookEvent.push(item.value)
        }
      })
      this.checkedKwaiEvent = []
      this.kwaiEventList.forEach(item => {
        if (tempArr.includes(item.value)) {
          this.checkedKwaiEvent.push(item.value)
        }
      })
      this.checkedTiktokEvent = []
      this.tiktokEventList.forEach(item => {
        if (tempArr.includes(item.value)) {
          this.checkedTiktokEvent.push(item.value)
        }
      })
    },
    platformLogo(platform) {
      return platformLogo(platform)
    },
    // 添加指标
    addFilterItems() {
      this.kpiForm.filterItems.push(
        {
          platform: '',
          os: '',
          country: '',
          standard: {
            condition: '',
            value: ''
          },
          exceed: {
            condition: '',
            value: ''
          }
        }
      )
    },
    // 移除指标
    removeFilterItems(index) {
      this.kpiForm.filterItems.splice(index, 1)
    },
    // 提交kpi指标
    async submitKpiTarget() {
      // if (this.kpiForm.filterItems.length === 0) return this.$message.warning('请完善指标')
      const obj = this.kpiForm.filterItems.find(item => {
        return item.platform === '' || item.os === '' || item.country === '' || item.standard.condition === '' || item.standard.value === ''
      })
      if (obj !== undefined) return this.$message.warning('请完善指标')
      // 后端框架接收null会转义此代码作为调整
      const temp = _.cloneDeep(this.kpiForm)
      temp.offerId = this.offerId
      temp.filterItems = temp.filterItems.map(item => {
        if (item.exceed.condition === '' || item.exceed.value === '' || JSON.stringify(item.exceed.condition) === '{}' || item.exceed.value === -1) {
          item.exceed = null
        }
        return item
      })
      // this.$emit('update:visible', false)
      const {data: res} = await submitKpiConfig(temp)
      if (res.code !== 200) return
      this.$message.success('保存成功')
      this.kpiDrawer = false
    },
    // 获取kpi数据
    async getKpiConfig() {
      const {data: res} = await getKpiConfig({offerId: this.offerId})
      if (res.data.id === undefined) return
      this.kpiForm.id = res.data.id
      this.kpiForm.target = res.data.target
      this.kpiForm.filterItems = res.data.filterItems
    },
    // 返回指标
    getTarget(target) {
      return this.orderTargetList.find(item => item.label === target).value
    }
  }
};
</script>

<style scoped lang="scss">
.search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}

.search-form {

  /deep/ .el-form-item {
    margin-bottom: 0;
  }

}

/deep/ .el-table__body-wrapper {
  z-index: 2
}

/deep/ .search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 6px;
}

* {
  box-sizing: border-box;
}

.header {

  .header-up {
    display: flex;
    justify-content: space-between;

    .date-template {
      .dt-item {
        display: inline-block;
        margin-bottom: 10px;
        margin-right: 10px;
      }
    }

  }

}

.el-select-dropdown.is-multiple .el-select-dropdown__item.selected::after ::v-deep {
  position: absolute;
  right: 3px;
  font-family: element-icons;
  content: "\e6da";
  font-size: 12px;
  font-weight: 700;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.tab-header {
  font-size: 14px;
  margin-bottom: 15px;

  .tab-header-left {
    float: left;

    & > * {
      margin-right: 15px;
    }
  }

  .tab-header-right {
    float: right;
  }
}

.bottom-page {
  margin-top: 15px;

  .el-pagination {
    float: right;
  }
}

.el-transfer {
  height: 100%;
  display: -webkit-box;

  /deep/ .el-transfer-panel {
    height: 100%;

    .el-transfer-panel__header {
      .el-checkbox {
        .el-checkbox__input {
          display: none;
        }
      }
    }

    .el-transfer-panel__body {
      height: 100%;

      .el-transfer-panel__list {
        height: 100%;
        padding-bottom: 100px;
      }
    }
  }
}

.el-select {
  width: 100%;
}

.drawer-box {
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
  height: 100%;

  .el-input {
    ::v-deep .el-input__inner {
      border-radius: 15px;
    }
  }

  .drawer-box-left {
    border: 1px solid #E8E8E8;
    border-radius: 5px;
    flex: 1;
    margin-right: 15px;
    display: flex;
    flex-direction: column;

    .drawer-box-left-input {
      padding: 15px 20px;
    }

    .drawer-box-left-tab {
      flex: 1;
      overflow: auto;

      .el-tabs {
        height: 100%;
        box-sizing: border-box;
        box-shadow: unset;
        border-bottom: unset;
        border-left: unset;
        border-right: unset;

        .el-checkbox-group {
          display: block;

          .el-checkbox {
            width: 25%;
          }

          .event-checkbox {
            width: 100%;
          }
        }
      }
    }
  }

  .drawer-box-right {
    width: 300px;
    border: 1px solid #E8E8E8;
    border-radius: 5px;
    padding: 15px 20px;
    display: flex;
    flex-direction: column;

    .select-label {
      line-height: 45px;
      height: 45px;
      font-size: 14px;
    }

    .tableHeaderOpt {
      flex: 1;
      overflow: auto;
    }
  }

  .drag-box {
    padding: 5px 0;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    cursor: move;

    .drag-box-left {
      color: #101010;
      font-size: 14px;

      i {
        margin-right: 18px;
      }
    }

    .drag-box-right {
      i {
        cursor: pointer;

        &:first-child {
          margin-right: 18px;
        }
      }
    }
  }
}

.forbid {
  cursor: default !important;
}

.kpi-box {
  padding: 0 15px;

  .el-table {
    ::v-deep .cell {
      display: flex;
    }

    .over-flow {
      overflow: hidden; //溢出内容隐藏
      text-overflow: ellipsis; //文本溢出部分用省略号表示
      white-space: nowrap;
    }
  }
}

.play-icon {
  display: inline-block;
  position: relative;

  &::before {
    content: '\ec61';
    font-family: 'myicon';
    font-size: 30px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #FFFFFF;
  }
}
</style>
